﻿using OrderControl;
using System;
using System.Linq;
using System.Windows.Forms;

namespace OrderControlWinForm {
    public partial class Form_Order : Form {
        private string stringCache;

        private Order usingOrder;
        public Order UsingOrder {
            get => usingOrder;
            set {
                usingOrder = value;
                bindingSource_Order.DataSource = value;
            }
        }

        public Form_Order() {
            InitializeComponent();
            this.UsingOrder = new Order(new Customer("Null", "Null"), DateTime.Now.Date, "Null");
        }

        public Form_Order(Order order) {
            InitializeComponent();
            this.UsingOrder = order;
            button_Cancel.Visible = false;
        }

        private void textBox_UnNullLimit_Enter(object sender, EventArgs e) {
            if(sender is TextBox textBox) {
                stringCache = textBox.Text;
            }
        }

        private void textbox_UnNullLimit_TextChanged(object sender, EventArgs e) {
            if(sender is TextBox textBox) {
                if (string.IsNullOrWhiteSpace(textBox.Text)) {
                    textBox.Text = stringCache;
                    MessageBox.Show("Text Cannot be null!");
                } else {
                    stringCache = textBox.Text;
                }
            }
        }

        private void button_Add_Click(object sender, EventArgs e) { 
            Form_Detail form_Detail = new Form_Detail();
            if (form_Detail.ShowDialog() == DialogResult.OK) {
                UsingOrder.Details.Add(form_Detail.Detail);
                bindingSource_Order.ResetBindings(false);
            }
        }

        private void button_Delete_Click(object sender, EventArgs e) {
            if (UsingOrder.Details.Any()) {
                UsingOrder.Details.Remove(UsingOrder.Details[dataGridView_OrderDetail.CurrentCell.RowIndex]);
                bindingSource_Order.ResetBindings(false);
            }
        }

        private void button_Edit_Click(object sender, EventArgs e) {
            if (UsingOrder.Details.Any()) {
                Form_Detail form_Detail = new Form_Detail(UsingOrder.Details[dataGridView_OrderDetail.CurrentCell.RowIndex]);
                form_Detail.ShowDialog();
                bindingSource_Order.ResetBindings(false);
            }
        }

        private void button_Ok_Click(object sender, EventArgs e) {
            this.DialogResult = DialogResult.OK;
        }

        private void button_Cancel_Click(object sender, EventArgs e) {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
